<template>
  <div class="api-manage-container">
    <div class="toolbar">
      <el-button type="primary" @click="handleCreateApi">
        <el-icon><Plus /></el-icon>新建接口
      </el-button>
      <el-input
        v-model="searchQuery"
        placeholder="搜索接口名称或路径"
        class="search-input"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>

    <el-table :data="apiList" style="width: 100%" v-loading="loading">
      <el-table-column prop="name" label="接口名称" min-width="150" />
      <el-table-column prop="path" label="请求路径" min-width="150" />
      <el-table-column prop="method" label="请求方法" width="100" />
      <el-table-column prop="type" label="接口类型" width="120">
        <template #default="{ row }">
          <el-tag
            :type="row.type === ApiType.DataSource ? 'success' : 'warning'"
          >
            {{ getApiTypeLabel(row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === ApiStatus.Enabled ? 'success' : 'info'">
            {{ row.status === ApiStatus.Enabled ? "启用" : "禁用" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template #default="{ row }">
          <el-button-group>
            <el-button
              type="primary"
              link
              :loading="row.testing"
              @click="handleTest(row)"
            >
              测试
            </el-button>
            <el-button type="primary" link @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">
              删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <ApiForm
      v-model:visible="formVisible"
      :edit-data="editingData"
      @submit="handleFormSubmit"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";
import { Plus, Search } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import ApiForm from "./components/ApiForm.vue";
import {
  getApiList,
  createApi,
  updateApi,
  deleteApi,
  testApi,
} from "@/api/apiManage";
import type { ApiConfig } from "@/types/api";
import { ApiStatus, ApiType } from "@/types/api";

const loading = ref(false);
const searchQuery = ref("");
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const formVisible = ref(false);
const editingData = ref<ApiConfig | null>(null);
const apiList = ref<ApiConfig[]>([]);

const getApiTypeLabel = (type: ApiType) => {
  const labels: Record<ApiType, string> = {
    [ApiType.DataSource]: "数据源接口",
    [ApiType.REST]: "REST接口",
  };
  return labels[type];
};

const loadData = async () => {
  loading.value = true;
  try {
    const params = {
      keyword: searchQuery.value,
      page: currentPage.value,
      pageSize: pageSize.value,
    };
    const { list, total: totalCount } = await getApiList(params);
    apiList.value = list;
    total.value = totalCount;
  } catch (error) {
    console.error("加载API列表失败:", error);
  } finally {
    loading.value = false;
  }
};

const handleCreateApi = () => {
  editingData.value = null;
  formVisible.value = true;
};

const handleEdit = (row: ApiConfig) => {
  editingData.value = { ...row };
  formVisible.value = true;
};

const handleTest = async (row: ApiConfig) => {
  if (!row.id) return;

  row.testing = true;
  try {
    const result = await testApi(row.id);
    if (result.success) {
      ElMessage.success(result.message);
    } else {
      ElMessage.error(result.message);
    }
  } catch (error) {
    ElMessage.error("测试失败");
  } finally {
    row.testing = false;
  }
};

const handleDelete = (row: ApiConfig) => {
  if (!row.id) return;

  ElMessageBox.confirm("确定要删除该接口吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    loading.value = true;
    try {
      await deleteApi(row.id);
      ElMessage.success("删除成功");
      loadData();
    } finally {
      loading.value = false;
    }
  });
};

const handleFormSubmit = async (data: ApiConfig) => {
  loading.value = true;
  try {
    if (data.id) {
      await updateApi(data.id, data);
      ElMessage.success("更新成功");
    } else {
      await createApi(data);
      ElMessage.success("创建成功");
    }
    loadData();
  } finally {
    loading.value = false;
  }
};

const handleSizeChange = (val: number) => {
  pageSize.value = val;
  loadData();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  loadData();
};

watch([searchQuery], () => {
  currentPage.value = 1;
  loadData();
});

loadData();
</script>

<style scoped>
.api-manage-container {
  padding: 20px;
}

.toolbar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

.search-input {
  width: 300px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 